import React, { useEffect } from "react";
import Banner from "../../components/Banner";
import "./index.css";
import ProductSection from "../../components/ProductSection";
import { useDispatch, useSelector } from "react-redux";
import {
    fetchSeckillProducts,
    fetchGroupBuyProducts,
    fetchProducts,
} from "../../store/slices/productsSlice";

import { ErrorBlock } from "antd-mobile";
import { useNavigate } from "react-router-dom";
// 组件封装的核心思路
// 求同->抽象->封装->复用
// 存异->暴露->定制
export default function HomePage() {
    const navigate = useNavigate();
    // dispatch 是用来发起 action 的
    const dispatch = useDispatch();
    // useSelector 用来获取 redux 中的状态
    const {
        seckillProducts,
        groupBuyProducts,
        allProducts,
        seckillLoading,
        groupBuyLoading,
        seckillError,
    } = useSelector((state) => state.products);
    // 异步的action需要在组件加载时发起
    useEffect(() => {
        dispatch(fetchSeckillProducts());
        dispatch(fetchGroupBuyProducts());
        dispatch(fetchProducts());
    }, [dispatch]);
    // 点击商品的处理函数
    const handleProductClick = ({ id }) => {
        navigate(`/product/${id}`);
    };
    return (
        <div className="home-page">
            <div className="home-header">
                <h2>振涛电商</h2>
            </div>
            <div className="home-content">
                <Banner />

                {seckillError ? (
                    <ErrorBlock status="default" />
                ) : (
                    <ProductSection
                        type="seckill"
                        title="限时秒杀"
                        products={seckillProducts}
                        loading={seckillLoading}
                        onProductClick={handleProductClick}
                    />
                )}

                <ProductSection
                    type="groupbuy"
                    title="限时团购"
                    products={groupBuyProducts}
                    loading={groupBuyLoading}
                    onProductClick={handleProductClick}
                />
            </div>
        </div>
    );
}
